package com.aizuda.boot.modules.business.contract.mapper;

import com.aizuda.boot.modules.business.contract.entity.ContractFieldValueEntity;
import com.aizuda.boot.modules.business.contract.entity.vo.ContractDTO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface ContractFieldValueMapper extends BaseMapper<ContractFieldValueEntity> {
    /**
     * 根据合同ID查询合同动态字段集合
     * @param contractId
     * @return
     */
    List<ContractFieldValueEntity> selectByContractId(@Param("contractId") Integer contractId);

    /**
     * 批量插入合同动态字段集合
     * @param list
     * @return
     */
    int batchInsert(@Param("list") List<ContractFieldValueEntity> list);

    /**
     * 批量更新合同动态字段集合
     * @param list
     * @return
     */
    int batchUpsert(@Param("list") List<ContractFieldValueEntity> list);


    @Select({
            "<script>",
            "SELECT * FROM contract_field_value ",
            "WHERE contract_id = #{contractId} ",
            "<if test='fieldIds != null and fieldIds.size() > 0'>",
            "  AND field_id IN ",
            "  <foreach item='fieldId' collection='fieldIds' open='(' separator=',' close=')'>",
            "    #{fieldId}",
            "  </foreach>",
            "</if>",
            "<if test='fieldIds == null or fieldIds.size() == 0'>",
            "  AND 1 = 0",  // 避免查询所有数据
            "</if>",
            "</script>"
    })
    List<ContractFieldValueEntity> findValuesByContractAndFields(
            @Param("contractId") Integer contractId,
            @Param("fieldIds") List<Long> fieldIds
    );

    /**
     * 根据合同ID查询合同动态字段集合（包含字段信息）
     * @param contractId
     * @return
     */
    @Select("SELECT " +
            "  cfv.field_id AS id, " +
            "  cfv.field_value AS fieldValue, " +
            "  cf.field_name AS fieldName, " +
            "  cf.code AS code, " +
            "  cf.field_type AS fieldType, " +
            "  cf.is_required AS isRequired " +
            "FROM " +
            "  contract_field_value cfv " +
            "JOIN " +
            "  contract_field cf ON cfv.field_id = cf.id " +
            "WHERE " +
            "  cfv.contract_id = #{contractId}")
    List<ContractDTO.ModuleDTO.FieldDTO> getFieldValuesWithFieldInfo(@Param("contractId") Integer contractId);

    /**
     * 根据字段code查询指定合同的指定字段值
     * @param contractId
     * @param code
     * @return
     */
    @Select("SELECT " +
            "cfv.field_value " +
            "FROM " +
            "contract_field cf " +
            "LEFT JOIN contract_field_value cfv ON cf.id = cfv.field_id " +
            "WHERE " +
            "cf.`code` = #{code} " +
            "AND cfv.contract_id = #{contractId}")
    String getFieldValueByCode(@Param("contractId") Integer contractId, @Param("code") String code);
}